//
//  ReadViewController.m
//  SimpleTimeDemo
//
//  Created by lanou3g on 15/11/13.
//  Copyright © 2015年 王丽珍. All rights reserved.
//

#import "ReadViewController.h"
#import "RESideMenu.h"
#import "ReadModel.h"
#import "MainDataHelper.h"
#import "ReadCollectionViewCell.h"
#import "UIImageView+WebCache.h"
#import "ReadDetailViewController.h"
@interface ReadViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, strong) NSMutableArray *readArray;
@property (nonatomic, strong) NSMutableArray *headerImageArray;


// 定时器
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) int page;

@end

@implementation ReadViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-menu"] style:UIBarButtonItemStylePlain target:self action:@selector(sec)];
    self.navigationController.navigationBar.translucent = NO;
    
    [self loadCollectionView];
    [self loadData];
    
    // Do any additional setup after loading the view.
}

- (void)loadCollectionView
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    float x = (self.view.frame.size.width - 30) / 3;
    flowLayout.itemSize = CGSizeMake(x, x);
    flowLayout.minimumInteritemSpacing = 5;
    flowLayout.minimumLineSpacing = 5;
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);

    _collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:flowLayout];
    
    
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = [UIColor whiteColor];
    
    
    
    UINib *nib = [UINib nibWithNibName:@"ReadCollectionViewCell" bundle:nil];
    [_collectionView registerNib:nib forCellWithReuseIdentifier:@"cell"];
    
    [self.view addSubview:self.collectionView];
    
    //给collectionView注册一个headerView
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
}


- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{

        UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
    
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 150)];
    _scrollView.pagingEnabled = YES;
    _scrollView.delegate = self;
    
    _scrollView.bounces = NO;
    
    [header addSubview:_scrollView];
    
    
    self.headerImageArray = [NSMutableArray array];
    NSString *string = @"http://api2.pianke.me/read/columns";
    NSString *bodyString = @"auth=CJdoEy6y9m3lDC8h8G8XilzJxQMevNrCEpDw6CjM0cWP22NFETh1d6fg&client=1&deviceid=2AD5AE2D-2FE5-4DF7-AB1E-150BCF01269E&version=3.0.6";
    [MainDataHelper postDataWithUrlString:string andBodyString:bodyString compare:^(id object) {
        NSDictionary *dic = object;
        //        NSLog(@"dic====%@",dic);
        NSArray *imageArray = dic[@"data"][@"carousel"];
        //        NSLog(@"dict2===%@",imageArray);
        
        for (NSDictionary *dic2 in imageArray) {
            ReadModel *model = [[ReadModel alloc] init];
            [model setValuesForKeysWithDictionary:dic2];
            [self.headerImageArray addObject:model];
        }
        
        //    NSLog(@"image=====%lu",(unsigned long)_headerImageArray.count);
        for (int i = 0; i < _headerImageArray.count; i++) {
            ReadModel *model = _headerImageArray[i];
            
            UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _headerImageArray.count * self.view.frame.size.width, 120)];
            UIImageView *headerImageView = [[UIImageView alloc] initWithFrame:CGRectMake(i * self.view.frame.size.width, 0, self.view.frame.size.width, 150)];
            [headerImageView sd_setImageWithURL:[NSURL URLWithString:model.img] placeholderImage:nil];
            [headView addSubview:headerImageView];
            [_scrollView addSubview:headView];
            
            
        }
        
        self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width * _headerImageArray.count, 0);
        
    }];
        return header;
}

//设置collectionView的header的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(self.view.frame.size.width, 150);
}

- (void)loadData
{
    self.readArray = [NSMutableArray array];
    NSString *string = @"http://api2.pianke.me/read/columns";
    NSString *bodyString = @"auth=CJdoEy6y9m3lDC8h8G8XilzJxQMevNrCEpDw6CjM0cWP22NFETh1d6fg&client=1&deviceid=2AD5AE2D-2FE5-4DF7-AB1E-150BCF01269E&version=3.0.6";

    [MainDataHelper postDataWithUrlString:string andBodyString:bodyString compare:^(id object) {
        NSDictionary *dic = object;
                NSLog(@"dic====%@",dic);
        NSArray *array = dic[@"data"][@"list"];
        
        for (NSDictionary *dic1 in array) {
            ReadModel *model = [[ReadModel alloc] init];
            [model setValuesForKeysWithDictionary:dic1];
            [self.readArray addObject:model];
        }
        
        NSLog(@"bbbb=====%lu",(unsigned long)_readArray.count);
        [_collectionView reloadData];
        
    }];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSLog(@"aaa=====%lu",(unsigned long)_readArray.count);
    return _readArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ReadModel *model = _readArray[indexPath.row];

    ReadCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor redColor];
    [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:model.coverimg] placeholderImage:nil];
//    cell.nameLabel.numberOfLines = 0;
//    [cell.nameLabel sizeToFit];
    
    //name的值长度不一样，采用拼接字符串
    cell.nameLabel.font = [UIFont systemFontOfSize:13];
    NSString *name = [NSString stringWithFormat:@"%@ ",model.name];
    NSString *nameStr = [name stringByAppendingString:model.enname];
    
    cell.nameLabel.text = nameStr;

    return cell;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    ReadDetailViewController *readDetail = [[ReadDetailViewController alloc] init];
    ReadModel *model = self.readArray[indexPath.row];
    readDetail.typeid = model.type;
    [self.navigationController pushViewController:readDetail animated:YES];
    
}



// 定时器放在viewwill里面
- (void)viewWillAppear:(BOOL)animated {
    self.timer = [NSTimer scheduledTimerWithTimeInterval:2.5 target:self selector:@selector(timer:) userInfo:nil repeats:YES];
    // 添加到主线程中去, 返回当前的消息循环对象
    [[NSRunLoop mainRunLoop]addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)timer:(NSTimer *)sender {
    self.page++;
    // 这里的self.page < 轮播图的个数 的这个你可以改数字,改了看看,juice知道是干什么的了
    if (self.page < 3) {
        [_scrollView setContentOffset:CGPointMake(self.page * self.view.frame.size.width, 0) animated:YES];
        
    }else {
        self.page = 0;
        [_scrollView setContentOffset:CGPointMake(self.page * self.view.frame.size.width, 0) animated:YES];
    }
}

//释放NSTimer
-(void)viewWillDisappear:(BOOL)animated
{
    [self.timer invalidate];
    self.timer = nil;
}



- (void)sec{
    [self.sideMenuViewController presentLeftMenuViewController];
        
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
